package com.jt.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * cookie API
 * @author dc
 * @Classname CookieUtil
 * @Date 2020/2/28 10:50
 */
public class CookieUtil {

    /**
     * 删除cookie
     * @param response 响应对象
     * @param cookieName cookie名字
     * @param domain cookie域
     * @param path 路径
     */
    public static void deleteCookie(HttpServletResponse response,String cookieName,String domain,String path){
        Cookie cookie = new Cookie(cookieName,"");
        cookie.setDomain(domain);
        cookie.setPath(path);
        //立即删除  -1:关闭会话时删除 0:立即删除
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    /**
     * 根据cookie名称获取cookie对象
     */
    public static Cookie getCookie(HttpServletRequest request,String cookieName){
        //1.动态获取指定的cookie信息
        Cookie[] cookies = request.getCookies();
        if(cookies!=null&&cookies.length>0){
            for(Cookie cookie:cookies){
                if(cookieName.equals(cookie.getName())){
                    return cookie;
                }
            }
        }
        return null;
    }


    /**
     * 根据cookie名称获取value值
     */
    public static String getCookieValue(HttpServletRequest request,String cookieName){
        Cookie[] cookies = request.getCookies();
        String ticket = null;
        if(cookies!=null&&cookies.length>0){
            for(Cookie cookie:cookies){
                if(cookieName.equals(cookie.getName())){
                    ticket=cookie.getValue();
                    break;
                }
            }
        }
        return ticket;
    }


}
